/**
 * Created by moyu on 2017/4/7.
 */

var MongoClient = require('mongodb').MongoClient,
    Db = require('mongodb').Db,
    assert = require('assert');


var url = 'mongodb://moyuyc:moyuyc@localhost:27017/custom_site';

Db.prototype.insertDocument = function (collectionName, data) {
    let collection = this.collection(collectionName);
    return new Promise((resolve, reject) => {
        collection.insertOne(data, function (err, result) {
            if (err) {
                console.error(err);
                reject(err);
            } else {
                resolve(result);
            }
        })
    })
};

Db.prototype.findDocuments = function (collectionName, data, handle) {
    let collection = this.collection(collectionName);
    handle = handle || function (x) {
            return x;
        };
    return new Promise((resolve, reject) => {
        handle(collection.find(data))
            .toArray(function (err, result) {
                if (err) {
                    console.error(err);
                    reject(err);
                } else {
                    // if (result.length)
                    resolve(result);
                    // else
                    //     reject(result);
                }
            })
    })
}

Db.prototype.findDocument = function (collectionName, data, options) {
    let collection = this.collection(collectionName);
    return new Promise((resolve, reject) => {
        collection.findOne(data, options, function (err, result) {
            if (err) {
                console.error(err);
                reject(err);
            } else {
                if (result)
                    resolve(result);
                else {
                    reject(result);
                }
            }
        })
    })
}

Db.prototype.deleteOneDocument = function (collectionName, data) {
    let collection = this.collection(collectionName);
    return new Promise((resolve, reject) => {
        collection.deleteOne(data, function (err, result) {
            if (err) {
                console.error(err);
                reject(err);
            } else {
                if (result.deletedCount > 0)
                    resolve(result);
                else {
                    reject(result);
                }
            }
        })
    })
};


module.exports = function () {
    if (_db) {
        return Promise.resolve(_db);
    } else {
        return connect();
    }
}

let _db;

process.on('exit', () => {
    _db && _db.close();
})

const connect = module.exports.connect = function () {
    return new Promise((resolve) => {
        MongoClient.connect(url, function (err, db) {
            assert.equal(null, err);
            _db = db;
            resolve(db);
        });
    })
}
